﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TcpProxy
{
    public abstract class ProtocolDecoder
    {
        const int DefaultForceTimeoutMs = 100;

        public BlockingStreamReader PacketStream { get; set; }

        public SessionState SessionState { get; set; }

        public TcpProxy TcpProxy { get; set; }

        public bool IsActive { get; set; }

        public bool ShouldExit { get; set; }

        System.Threading.Thread _decoderThread;

        public void Start()
        {
            ShouldExit = false;
            IsActive = true;

            _decoderThread = new System.Threading.Thread(new System.Threading.ThreadStart(DecoderMain));
            _decoderThread.Name = "Decoder";
            _decoderThread.Start();
        }

        public void Stop()
        {
            Stop(DefaultForceTimeoutMs);
        }

        public void Stop(int forceTimeoutMs)
        {
            if (!IsActive) return;
            if (forceTimeoutMs <= 0) throw new Exception("Invalid timeout!");

            ShouldExit = true;
            DateTime startTime = DateTime.Now;
            while (IsActive)
            {
                System.Threading.Thread.Sleep(100);
                if (DateTime.Now.Subtract(startTime).TotalMilliseconds > forceTimeoutMs)
                {
                    _decoderThread.Abort();
                    IsActive = false;
                    return;
                }
            }
        }

        public virtual void DecoderMain()
        {
            throw new NotImplementedException();
        }
    }
}
